package com.zyt.wiki.controller;

import com.zyt.wiki.exception.BusinessException;
import com.zyt.wiki.resp.CommonResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理、数据预处理等
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    public static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class) ;

    /** 校验异常统一处理 */
    @ExceptionHandler(value = BindException.class)  //针对BindException进行处理
    @ResponseBody                                   // 返回Json格式报文
    public CommonResp validExceptionHandler(BindException e){
        CommonResp resp = new CommonResp() ;
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage() ;
        LOG.warn("参数校验失败: {}", message);
        resp.setSuccess(false);
        resp.setMessage(message);
        return resp ;
    }

    /** 校验异常统一处理 */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResp validExceptionHandler(BusinessException e){
        CommonResp resp = new CommonResp() ;
        String message = e.getCode().getDesc() ;
        LOG.warn("业务异常: {}", message) ;
        resp.setSuccess(false) ;
        resp.setMessage(message) ;
        return resp ;
    }

    /** 校验异常统一处理 */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResp validExceptionHandler(Exception e){
        CommonResp resp = new CommonResp() ;
        LOG.error("系统异常: {}", e) ;
        resp.setSuccess(false) ;
        resp.setMessage("系统出现异常，请联系管理员") ;
        return resp ;
    }

}
